<?php
namespace app\admin\model;

use think\Db;

use think\Model;

class Users extends Model
{
	//定义主键
	protected $pk = 'uid';
	//开启自动写入时间戳
	protected $autoWriteTimestamp = true;
	// 定义时间戳字段名
	protected $createTime = 'addtime';
	protected $updateTime = 'updatetime';
	// 设置当前模型对应的完整数据表名称
    protected $table = 'user';
	
    /**
     * 获取最大的id值
     * Enter description here ...
     */
	protected function subQuery()
	{
		//子查询，查询uid值最大的
			$subQuery = Db::table($this->table)->field('max(uid)')->buildSql();//->fetchSql(true) 也可以
			return $subQuery;
	}
	/**
	 * 根据添加时间获取最大值那条
	 * Enter description here ...
	 */
	public function getLastInfo()
	{
//		$user = Db::query("SELECT * FROM `user` WHERE uid = (SELECT MAX(uid) FROM `user`  WHERE `status`=1)");
		$user = Db::table('user')->order('addtime DESC')->limit(1)->find();
		return $user;
	}
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $l
	 */
	public function getCount($l)
	{
		$count = Db::table($this->table)->where([
			'level'=>['=',$l],
			'status'=>['=',1]		
		])->count();
		return $count;
	}
	public function getFirstUser(){
		$user = Db::table($this->table)->where('level','=',1)->find();
		return $user;
	}
	
	public function getParentUser($lev,$p)
	{
		if($p==1){//本层已经满了
			$parentUser = Db::table('user')->where([
				'status'=>['=',1],
				'level'=>['=',$lev],//查询本级信息做为下一个用户的上级信息
			])->order('addtime ASC')->limit(1)->find();
		}elseif($p==2){//本层未满
//			//构建子查询
//			 $subQuery = Db::table('user')->where([
//				'status'=>['=',1],
//				'level'=>['=',$lev],
//			])->field('fid')->buildSql();
//			//查询没有子用户的
//			$temp = Db::table('user')->where([
//				'status'=>['=',1],
//				'level'=>['=',$lev-1],//查询上级信息，做为下一个用户的上级信息
//			])->where('uid','NOT IN',$subQuery)->order('addtime ASC')->limit(1)->buildSql();
//			var_dump($temp);
				$temp = Db::query("SELECT * FROM `user`  WHERE `status`=1 AND `level`=?
						AND uid NOT IN (SELECT fid FROM `user` WHERE `status`=1 AND `level`=?)
 						ORDER BY `addtime` ASC LIMIT 0,1",[$lev-1,$lev]);
			if(empty($temp)){
				$t = Db::query("SELECT * FROM `user` u1  WHERE `status`=1 AND `level`=?
				AND uid = (SELECT fid FROM `user` u2 WHERE u1.uid = u2.fid AND `status`=1 AND `level`=? GROUP BY u2.fid HAVING COUNT(*)=1)
 				ORDER BY `addtime` ASC LIMIT 1",[$lev-1,$lev]);
				$parentUser = $t[0];
			}else{
				$parentUser = $temp[0];
			}
		}
		return $parentUser;
	}
	
}